package com.sw.study.springbootstudy.controller;

import com.sw.study.springbootstudy.domain.TableDataInfo;
import com.sw.study.springbootstudy.framework.BaseController;
import com.sw.study.springbootstudy.pojo.Article;
import com.sw.study.springbootstudy.service.IArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author sw
 * @project springboot-study
 * @description  文章处理类
 * @date 2020/4/22 09:33
 */

@RestController
@RequestMapping("/article")
public class ArticleController extends BaseController {
    @Autowired
    private IArticleService articleService;
    /**
     * 查询所有文章信息 分页
     * @return
     */
    @RequestMapping("/pageArticle")
    public String  pageArticle(Model model, Integer pageNum,Integer pageSize){
        startPage();
        if(pageNum==null){
            pageNum=1;
        }
        if(pageSize==null){
            pageSize=2;
        }
        List<Article> articles=articleService.queryArticles();
        TableDataInfo dataTable = getDataTable(articles);

       // model.addAttribute("tableDataInfo",dataTable);
        model.addAttribute("articles",articles);
        //上一页逻辑
        if(pageNum>1){
            model.addAttribute("beforeNum",pageNum-1);
            //model.addAttribute("isHave",true);
        }
        //下一页逻辑
        Integer totalPage= Math.toIntExact((dataTable.getTotal() + pageSize - 1) / pageSize);
        model.addAttribute("totalPage",totalPage);
        if(totalPage>pageNum){
            model.addAttribute("afterNum",pageNum+1);
            //model.addAttribute("isNext",true);
        }
        return "client/index";
    }

    @RequestMapping("/selectById")
    public Article selectById(Integer id){
        return articleService.selectById(id);
    }

    @RequestMapping("/updateArticle")
    public Article updateArticle(String title,Integer id){
        Article article = articleService.selectById(id);
        article.setTitle(title);
        articleService.upadteArticle(article);
        return article;
    }

    @RequestMapping("/deleteById")
    public void deleteArticleById(Integer id){
        articleService.deleteArticle(id);
    }

}
